package com.oa.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.joneying.common.annotation.CommonService;
import com.joneying.common.web.response.Resp;
import com.oa.admin.dto.OvertimeApplyAddDTO;
import com.oa.admin.dto.OvertimeApplyListDTO;
import com.oa.admin.entity.OvertimeApply;
import com.oa.admin.entity.UserHoliday;
import com.oa.admin.mapper.OvertimeApplyMapper;
import com.oa.admin.service.IOvertimeApplyService;
import com.oa.admin.service.IUserHolidayService;
import com.oa.admin.vo.OvertimeApplyListVO;
import com.oa.core.PageResult;
import com.oa.core.enumm.ProcessDefineEnum;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.core.utils.DateUtil;
import com.oa.core.utils.ExcelUtil;
import com.oa.system.dto.ApplyApprovalAddDTO;
import com.oa.system.dto.ApprovalDTO;
import com.oa.system.entity.ApplyApproval;
import com.oa.system.entity.User;
import com.oa.system.service.IApplyApprovalService;
import com.oa.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;

@Service
public class OvertimeApplyServiceImpl extends ServiceImpl<OvertimeApplyMapper, OvertimeApply> implements IOvertimeApplyService {

    @Autowired
    private OvertimeApplyMapper overtimeApplyMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IApplyApprovalService applyApprovalService;

    @Autowired
    private IUserHolidayService userHolidayService;

    @CommonService
    @Override
    public PageResult<OvertimeApplyListVO> findOvertimeApplyList(OvertimeApplyListDTO overtimeApplyListDTO) {
        Page page = overtimeApplyListDTO.getPage();
        return new PageResult<>(overtimeApplyMapper.findOvertimeApplyList(page, overtimeApplyListDTO), page);
    }

    @CommonService
    @Override
    public OvertimeApplyListVO findOvertimeApplyDetails(String id) {
        return overtimeApplyMapper.findOvertimeApplyDetails(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @CommonService
    @Override
    public Resp add(String userId, OvertimeApplyAddDTO overtimeApplyAddDTO) throws BusinessException {
        OvertimeApply overtimeApply = new OvertimeApply();
        BeanUtils.copyProperties(overtimeApplyAddDTO, overtimeApply);
        User user = userService.selectById(userId);
        overtimeApply.setUserId(user.getId());
        if(insert(overtimeApply)){
            ApplyApprovalAddDTO applyApprovalAddDTO = new ApplyApprovalAddDTO();
            applyApprovalAddDTO.setApplyId(overtimeApply.getId());
            applyApprovalAddDTO.setApplyApprovalName(user.getName() + ProcessDefineEnum.OVERTIME.getText());
            applyApprovalAddDTO.setApprovalProcessId(ProcessDefineEnum.OVERTIME.getId());
            applyApprovalAddDTO.setApprovalUserId(user.getId());
            applyApprovalAddDTO.setApprovalPlanId(Long.valueOf(0));
            return applyApprovalService.addApproval(applyApprovalAddDTO);
        }
        throw new BusinessException("添加申请失败!");
    }

    @Transactional(rollbackFor = Exception.class)
    @CommonService
    @Override
    public Resp audit(String id, String applyId, String remark, Integer status) throws DataIsEmptyException, BusinessException {
        OvertimeApply overtimeApply = selectById(applyId);
        overtimeApply.setRemark(remark);
        if(updateById(overtimeApply)){

            ApprovalDTO approvalDTO = new ApprovalDTO();
            approvalDTO.setId(Long.valueOf(id));
            approvalDTO.setStatus(status);

            return applyApprovalService.audit(approvalDTO, d -> {
                if(d.getStatus() == 2){
                    if(d.isLastStatus()){
                        UserHoliday userHoliday = userHolidayService.selectOne(new EntityWrapper().eq("holiday_id", 4).eq("user_id", d.getApplyApproval().getApprovalUserId()));

                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(overtimeApply.getStartTime());
                        Integer startTime = calendar.get(Calendar.HOUR_OF_DAY);

                        calendar.setTime(overtimeApply.getEndTime());
                        Integer endTime = calendar.get(Calendar.HOUR_OF_DAY);

                        double hour = endTime - startTime;

                        userHoliday.setSurplusDay((userHoliday.getSurplusDay() + hour) / 10);
                        userHolidayService.updateById(userHoliday);
                    }
                }
            });
        }
        throw new BusinessException("审批失败!");
    }

    @Override
    public void export(OvertimeApplyListDTO overtimeApplyListDTO, HttpServletResponse response){
        List<OvertimeApplyListVO> overtimeApplyListVOS = null;
        if(overtimeApplyListDTO.getPage() != null){
            Page<OvertimeApplyListVO> page = new Page(Integer.valueOf(overtimeApplyListDTO.getPageNum()), Integer.valueOf(overtimeApplyListDTO.getPageSize()));
            overtimeApplyListVOS = overtimeApplyMapper.findOvertimeApplyList(page, overtimeApplyListDTO);
        }else{
            overtimeApplyListVOS = overtimeApplyMapper.findOvertimeApplyList(new Page(), overtimeApplyListDTO);
        }
        String[] rows = {"id", "申请ID", "名称", "部门", "请假原因", "开始时间", "结束时间", "审批节点", "审核状态", "审核状态备注", "创建时间"};
        try {
            ExcelUtil.downloadExcel("加班申请列表" + DateUtil.getDayMonth(), rows, overtimeApplyListVOS, "加班申请列表" + DateUtil.getDayMonth()+".xls", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
